package com.woniuxy.usercoachassemble.commons;

import java.io.InputStream;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * 
 * @ClassName:  QiNiuUtils   
 * @Description:TODO(七流云图片上传工具)   
 * @author: Fy浪迹、
 * @date: 2020-06-12 04:53:11
 */
public class QiNiuUtils {
	
	// 设置需要操作的账号的AK和SK
    private static final String ACCESS_KEY = "QvnFAdIGECkNziq61ZoS4RwC14Yc_HPfiY3Yn0rC";
    private static final String SECRET_KEY = "pBCW1cLoPS9KFGWJxJKrT8F-R9P4Wnx-mtvhhEIW";

    // 要上传的空间名称
    private static final String BUCKETNAME = "yoga44";
    // CDN外域域名
    private static final String CDN_DOMAIN = "qd786hos4.bkt.clouddn.com";
    
    // 判断文件是否上传成功
    private static final String SUCCESS = "success";
    
    /**
     * 
     * @Title: uploadQNImg   
     * @Description: TODO(上传文件到七牛云)   
     * @param file   上传文件的输入流
     * @param fileName 上传文件的名称(自定义)
     * @return      
     * String      
     * @throws
     * @author: Fy浪迹、
     * @date 2020-06-12 04:59:34
     */
    
    public static String uploadQNImg(InputStream file, String fileName) {
    	//提供配置信息
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKETNAME);
        
        Response response = null;
        try {
            //上传
        	response = uploadManager.put(file, fileName, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        	
        } catch (QiniuException e) {
            throw new RuntimeException("上传文件出错", e);
        }
        return "success";
    }
    
    /**
     * @Title: fullPath   
     * @Description: TODO(获取存入文件到七牛云成功后，映射的网络地址)   
     * @param fileName 存入七牛云的文件名称包括后缀 
     * @return      
     * String      
     * @throws
     * @author: Fy浪迹、
     * @date 2020-06-12 05:03:52
     */
    public static String fullPath(String fileName) {
        return "http://"+CDN_DOMAIN +"/" +fileName;
    }

}
